package com.neusoft.bizcore.notice.notification.repository.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.notice.notification.model.NoticeTemplate;
import com.neusoft.bizcore.notice.notification.model.QNoticeTemplate;
import com.neusoft.bizcore.notice.notification.repository.CustomizedNoticeTemplateRepository;
import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedNoticeTemplateRepositoryImpl extends AbstractRepository
        implements CustomizedNoticeTemplateRepository {

    @Override
    public List<NoticeTemplate> index(final Searchable searchable) {
        final QNoticeTemplate qNoticeTemplate = QNoticeTemplate.noticeTemplate;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<NoticeTemplate> query = this.query().selectFrom(qNoticeTemplate);
        query.where(where);
        return query.fetch();
    }

    @Override
    public Page<NoticeTemplate> search(final Pageable pageable, final Searchable searchable) {
        final QNoticeTemplate qNoticeTemplate = QNoticeTemplate.noticeTemplate;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<NoticeTemplate> query = this.query().selectFrom(qNoticeTemplate);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return NoticeTemplate.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QNoticeTemplate qNoticeTemplate = QNoticeTemplate.noticeTemplate;
        if (StringUtils.isNotBlank(searchable.getStrValue("name"))) {
            where.and(super.containsStr(qNoticeTemplate.name, searchable, "name"));
        }
        return where;
    }

}
